<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Athlete;
use App\Model\Team;
use Illuminate\Support\Facades\Hash;

class AthleteController extends Controller
{
    //运动员列表
    function index(){
        $data = Athlete::paginate(8);
        return view('admin.athlete.index',['data' => $data]);
    }

    // 新增运动员
    function add(Request $request){
        $teams = Team::all();
        if($request->isMethod('POST')){
            $data = $request->input('athlete');
            $new_athlete = new Athlete();
            $new_athlete->name = $data['name'];
            $new_athlete->login_name = $data['login_name'];
            $new_athlete->password = bcrypt($data['name']);
            $new_athlete->sex = $data['sex'];
            $new_athlete->birthday = $data['birthday'];
            $new_athlete->height = $data['height'];
            $new_athlete->weight = $data['weight'];
            $new_athlete->phone = $data['phone'];
            $new_athlete->team_id = $data['team_id'];

            if($new_athlete->save()){
                return redirect('admin/sport/athlete')->with('success',"新增运动员成功");
            }else{
                return redirect()->back();
            }
        }

        return view('admin.athlete.add',['teams' => $teams]);
    }

    // 编辑运动员
    function update(Request $request,$id){
        // 查出当前运动员信息
        $athlete = Athlete::find($id);
        // 查出所有团队信息
        $teams = Team::all();
        // 如果请求方式为
        if($request->isMethod('POST')){
            // 获取到页面的表单
            $data = $request->input('athlete');
            // 重新给运动员赋值
            $athlete->name = $data['name'];
            $athlete->login_name = $data['login_name'];
            $athlete->sex = $data['sex'];
            $athlete->birthday = $data['birthday'];
            $athlete->height = $data['height'];
            $athlete->weight = $data['weight'];
            $athlete->phone = $data['phone'];
            $athlete->team_id = $data['team_id'];

            // 判断有输入密码：输入则重置，没输入就不变
            if($data['password']!=null){
                $athlete->password = bcrypt($data['password']);
            }

            // 将当前运动员信息更新
            if($athlete->save()){
                return redirect('admin/sport/athlete')->with('success',"修改运动员信息成功");
            }else{
                // 失败则返回
                return redirect()->back();
            }
        }
        // 默认get请求，将当前运动员信息和全部团队信息带到页面
        return view('admin.athlete.update',['athlete' => $athlete,'teams' => $teams]);
    }

    //根据id删除数据
    function remove($id){
        // 根据id查出当前用户
        $cur_data = Athlete::find($id);
        
        //调用delete()函数删除数据，并重定向返回视图，将一次性信息存到session
        if($cur_data->delete()){
            return redirect('admin/sport/athlete')->with('success','删除成功');
        }

        return redirect('admin/sport/athlete')->with('error','删除失败');
    }
}
